﻿using JmShared;
using Newtonsoft.Json;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocketServer.Filters;
using WebSocketServer.Utilities;

namespace WebSocketServer.Commands
{
    [LoggedInValidationFilter(Order = 0)]
    [LogTimeCommandFilter(Order = 1)]
    public class RequestAvatar : JsonSubCommand<JiveClientSession, AvatarRequest>
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


        protected override void ExecuteJsonCommand(JiveClientSession session, AvatarRequest request)
        {
            AvatarTransfer avatar = DB.DbManager.ReadAvatarTransfer(request.DeviceID, request.Username);
            if (avatar != null)
            {
                //if (avatar.AvatarByteArray.Length < 5000)
                //{

                    if (session.SendAvatar(avatar))
                        log.Debug(string.Format("Sent avatar {0} from {1} to {2}", avatar.Hash, avatar.SenderID, session.ChatClient.Username));
                    else
                        log.Warn(string.Format("Failed to send avatar to user {0}", session.ChatClient.Username));
                //}
                //else //We need to send in chunks
                //{
                //    string data = JsonConvert.SerializeObject(avatar);
                //    List<string> chunks = SharedStaticMethods.SplitLongMessage(data, 5000); //We send in chunks of 5KB
                //    int i = 1;
                //    string id = new ShortGuid(Guid.NewGuid());
                //    foreach (string chunk in chunks)
                //    {
                //        FileSlice slice = new FileSlice() { Data = chunk, SliceCount = chunks.Count, SliceNumber = i, TransferID = id, TransferType = FileTransferType.Avatar };
                //        session.SendFileSlice(slice);
                //        i++;
                //    }
                //}
            }
            else
                log.Warn(string.Format("Could not find avatar for user {0} in database. Send aborted", request.Username));
        }
    }
}
